package com.lepu.app.fun.tool.bbcsz;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.app.config.UserConfig;
import com.app.utils.Const;
import com.app.utils.DateUtil;
import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.ui.wheel.WheelView;
import com.core.lib.utils.DateType;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.fun.tool.bbcsz.bean.BeanToolBbcs;
import com.lepu.app.fun.tool.cjsj.bean.BeanToolChanJian;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

public class BbcsActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener,AsyncRequest {
	private String REQUEST_DATA = "request_data";
	
	private EditText mBabyName;
	private EditText mBabyWeight;
	private TextView mBabyDate;
	private TextView mBabyTime;
	private EditText mFatherName;
	private EditText mMotherName;
	
	private LinearLayout mYesTextView;
	private LinearLayout mNoTextView;
	
	private static BbcsActivity mInstance;
	@Override
	public void onCreate(Bundle savedInstanceState) {

		mNeedStatusBar = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tool_bbcs_activity);

		UtilityBase.setStatusBarRes(this, R.color.color_taidong, true);
		mInstance = this;
		init();
	}

	@Override
	public void onResume() {
		super.onResume();
		
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		mInstance = null;
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	public static BbcsActivity getInstance(){
		return mInstance;
	}
	
	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("宝宝出生证");
		topbar.setTopbarBackground(R.color.color_taidong);
		topbar.setonTopbarNewLeftLayoutListener(this);
		
		mBabyName = (EditText) findViewById(R.id.babyNameText);
		mBabyWeight = (EditText) findViewById(R.id.babyWeightText);
		mBabyDate = (TextView) findViewById(R.id.dateText);
		mBabyTime = (TextView) findViewById(R.id.timeText);
		mFatherName = (EditText) findViewById(R.id.fatherText);
		mMotherName = (EditText) findViewById(R.id.motherText);
		
		mYesTextView = (LinearLayout) findViewById(R.id.yesText);
		mNoTextView = (LinearLayout) findViewById(R.id.noText);
		
		
		mBabyDate.setOnClickListener(onClick);
		mBabyTime.setOnClickListener(onClick);
		mYesTextView.setOnClickListener(onClick);
		mNoTextView.setOnClickListener(onClick);
		
		mBabyWeight.addTextChangedListener(new CustomTextWatcher(mBabyWeight));
		
		mYesTextView.setSelected(true);
		mBabyDate.setText(DateUtilBase.stringFromDate(new Date(), DateUtilBase.YEAR_MONTH_DAY));
		mBabyTime.setText(DateUtilBase.stringFromDate(new Date(),DateUtilBase.DATE_HOUR_MINUTE));
		
	}

	@SuppressLint("DefaultLocale")
	public void viewClick(View view) {
		int rid = view.getId();
		switch (rid) {
		case R.id.testButton:
			String babyName = mBabyName.getText().toString().trim();
			String babyWeight = mBabyWeight.getText().toString().trim();
			String babyDate = mBabyDate.getText().toString().trim();
			String babyTime = mBabyTime.getText().toString().trim();
			String fatherName = mFatherName.getText().toString().trim();
			String motherName = mMotherName.getText().toString().trim();

			if (TextUtils.isEmpty(babyName)) {
				UIHelper.showToast(this, "请填写宝宝姓名");
				return;
			}
			
			if(babyName.length()<2 || babyName.length()>20){
				UIHelper.showToast(this, "请填写2~20字宝宝姓名");
				return;
			}
			
			if (TextUtils.isEmpty(babyWeight)) {
				UIHelper.showToast(this, "请填写宝宝体重");
				return;
			}
			
			if(TextUtils.isEmpty(babyDate)){
				UIHelper.showToast(this, "请填写出生日期");
				return;
			}
			if(TextUtils.isEmpty(babyTime)){
				UIHelper.showToast(this, "请填写出生时间");
				return;
			}
			if(fatherName.length()>0){
				if(fatherName.length()<2 || fatherName.length()>20){
					UIHelper.showToast(this, "请填写2~20字宝爸姓名");
					return;
				}
			}
			
			if(motherName.length()>0){
				if(motherName.length()<2 || motherName.length()>20){
					UIHelper.showToast(this, "请填写2~20字宝妈姓名");
					return;
				}	
			}
			
//			if(TextUtils.isEmpty(fatherName)){
//				UIHelper.showToast(this, "请填写宝爸姓名");
//				return;
//			}
//			if(TextUtils.isEmpty(motherName)){
//				UIHelper.showToast(this, "请填写宝妈姓名");
//				return;
//			}
			
			
			int sex = 1;
			if(mYesTextView.isSelected()){
				sex =1;
			}
			
			if(mNoTextView.isSelected()){
				sex =2;
			}
			
			BeanToolBbcs bean = new BeanToolBbcs();
			bean.babyName = babyName;
			bean.babySex = sex;
			bean.babyWeight = babyWeight;
			bean.babyDate = babyDate;
			bean.babyTime = babyTime;
			bean.fatherName = fatherName;
			bean.motherName = motherName;
			
			Intent intent = new Intent(BbcsActivity.this,BbcsShowActivity.class);
			Bundle bundle = new Bundle();
        	bundle.putSerializable("bbcs", bean);
        	intent.putExtras(bundle);
            startActivity(intent,true);
            
//          Intent intent = new Intent(BbcsActivity.this,AppBroswerActivity.class);
//          intent.putExtra("url", "http://dl.eyzhs.com/tools/birthCertificate.html?name=%E5%95%8A%E5%95%8A&gender=2&weight=1&father=%E5%A7%90%E5%A7%90&mother=%E5%93%A6%E5%93%A6&birthday=2016-06-17%2013:41");
//          startActivity(intent,true);
			break;

		default:
			break;
		}
	}
	
	View.OnClickListener onClick = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.dateText:
				showBirthDateDialog(mBabyDate);
				break;
			case R.id.timeText:
				showTimeDialog(mBabyTime);
				break;
			case R.id.yesText:
				mYesTextView.setSelected(true);
				mNoTextView.setSelected(false);
				
				break;
			case R.id.noText:
				mYesTextView.setSelected(false);
				mNoTextView.setSelected(true);
				
				break;
			default:
				break;
			}
		}
	};
	
	//上传
	public void request(BeanToolChanJian bean) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			
			params.put("CheckDate", bean.date);
			params.put("CheckItems", bean.note);
			params.put("IsAlert", bean.remindIs);
			params.put("AlertBeforeDay", bean.remindIndex);
			params.put("AlertTime", bean.remindTime);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post_main(Setting.getUploadChanjianUrl(), map, null, this,REQUEST_DATA, true, false);
	}
	

	private void showBirthDateDialog(final TextView textView) {
		String babyDate = UserConfig.getConfigString(BbcsActivity.this, Const.CONFIG_APP_BABY_DATE, "");
		String dateStr = "";
		if (TextUtils.isEmpty(babyDate)) {
			dateStr = DateUtilBase.stringFromDate(new Date(),DateUtilBase.YEAR_MONTH_DAY);
		} else {
			Date date = DateUtilBase.dateFromString(babyDate,DateUtilBase.YEAR_MONTH_DAY);
			dateStr = DateUtilBase.stringFromDate(date,DateUtilBase.YEAR_MONTH_DAY);
		}

		Date date = DateUtilBase.dateFromString(dateStr,DateUtilBase.YEAR_MONTH_DAY);
		MyDialog dialog = new MyDialog(BbcsActivity.this)
				.setTitle("请选择宝宝出生日期")
				.setDateTimePicker(date, DateType.YEAR_MONTH_DAY)
				.setNegativeButton(R.string.app_cancel,
						new View.OnClickListener() {

							@Override
							public void onClick(View arg0) {

							}
						})
				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// 如果是个数,则显示为"02"的样式
						WheelView wv_year = (WheelView) v
								.findViewById(R.id.year);
						WheelView wv_month = (WheelView) v
								.findViewById(R.id.month);
						WheelView wv_day = (WheelView) v.findViewById(R.id.day);

						String parten = "00";
						DecimalFormat decimal = new DecimalFormat(parten);
						// 设置日期的显示
						String text = (wv_year.getCurrentItem() + MyDialog.START_YEAR)
								+ "-"
								+ decimal.format((wv_month.getCurrentItem() + 1))
								+ "-"
								+ decimal.format((wv_day.getCurrentItem() + 1));

						if(DateUtil.getLongTime(text) > DateUtil.getLongTime(DateUtil.stringFromDate(new Date(), DateUtilBase.YEAR_MONTH_DAY))){
							UIHelper.showToast(BbcsActivity.this, "不能选择未来时间");
						}else{
							textView.setText(text);
						}
						
					}
				});

		dialog.create(null).show();
	}
	

	// 弹出时间选择器 hh:mm
	private void showTimeDialog(final TextView textView) {

		String dateStr = DateUtilBase.stringFromDate(new Date(),DateUtilBase.DATE_HOUR_MINUTE);

		Date date = DateUtilBase.dateFromString(dateStr,DateUtilBase.DATE_HOUR_MINUTE);
		MyDialog dialog = new MyDialog(BbcsActivity.this)
				.setTitle("请选择宝宝出生时间")
				.setTimePicker(date)
				.setNegativeButton(R.string.app_cancel,
						new View.OnClickListener() {

							@Override
							public void onClick(View arg0) {

							}
						})
				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						WheelView wv_hour = (WheelView) v
								.findViewById(R.id.hour);
						WheelView wv_minute = (WheelView) v
								.findViewById(R.id.minute);

						String parten = "00";
						DecimalFormat decimal = new DecimalFormat(parten);
						// 设置日期的显示
						String text = decimal.format((wv_hour.getCurrentItem()))
								+ ":"
								+ decimal.format((wv_minute.getCurrentItem()));
						
						textView.setText(text);
					}
				});

		dialog.create(null).show();
	}
	
	class CustomTextWatcher implements TextWatcher {

		EditText contentEditText;

		public CustomTextWatcher(EditText editText) {
			contentEditText = editText;
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			String content = s.toString().trim();

			if (TextUtils.isEmpty(content)) {

			} else {
				// new
				if (content.contains(".")) {
					if (s.length() - 1 - content.indexOf(".") > 2) {
						s = content.subSequence(0,
								content.indexOf(".") + 3);
						contentEditText.setText(s);
						contentEditText.setSelection(s.length());
					}
				}
				
				if (content.substring(0).equals(".")) {
					s = "0" + s;
					contentEditText.setText(s);
					contentEditText.setSelection(2);
				}

				if (content.startsWith("0")
						&& content.length() > 1) {
					if (!content.substring(1, 2).equals(".")) {
						contentEditText.setText(s.subSequence(0, 1));
						contentEditText.setSelection(1);
						return;
					}
				}
				
				//小数点前限制前3位
				int value = UtilityBase.parseInt(content);
				if(value >= 1000){
					content = content.substring(0,3);
					contentEditText.setText(content);
					contentEditText.setSelection(content.length());
				}
			}
		}

		@Override
		public void afterTextChanged(Editable s) {

		}
	}
	
	@Override
	public void RequestComplete(Object arg0, Object arg1) {
		ObserverManager.getInstance().notify(ObserverConst.NOTIFY_CHANJIAN_CHANGE, null,null);
		hideProgressDialog();
		finish(true);
	}

	@Override
	public void RequestError(Object arg0, int arg1, String arg2) {
		ObserverManager.getInstance().notify(ObserverConst.NOTIFY_CHANJIAN_CHANGE, null,null);
		hideProgressDialog();
		finish(true);
	}
	
}
